<template>
  <div style="width: 100%" >
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">

      <!--查询表单-->
      <el-form :inline="true" :model="user" :rel="user"

               class="demo-form-inline">

        <el-form-item label="部门" class="formitem" >
          <el-select v-model="user.departmentId" placeholder="请选择">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <el-tag size="mini" effect="plain" type="success">
                  {{ item.deptCount }}人
                </el-tag>
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户名" class="formitem" >
          <el-input   v-model="user.username" placeholder="用户名"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" class="formitem" >
          <el-input  v-model="user.email" placeholder="邮箱"></el-input>
        </el-form-item>

        <el-form-item label="性别" class="formitem" >
          <el-radio v-model="user.sex" label=0>男</el-radio>
          <el-radio v-model="user.sex" label=1>女</el-radio>
          <el-radio  v-model="user.sex"  label=null  >全部</el-radio>
        </el-form-item>

        <el-form-item label="昵称" class="formitem" >
          <el-input v-model="user.nickname" placeholder="昵称"></el-input>
        </el-form-item>

        <el-form-item class="formitem" >
          <el-button @click="resetUser()">重置</el-button>
          <el-button type="primary" @click="onSubmit" >查询</el-button>
          <el-button type="success" @click="insertDialog=true" >添加</el-button>
          <el-button type="info" @click="exportExcel()" >导出</el-button>
        </el-form-item>

      </el-form>

      <el-table
        :data="tableData"
        border
        style="width: 100%;height: 375px"
        max-height="375px">
        <el-table-column
          prop="id"
          label="编号"
        width="60px">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="100px">
        </el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="80px">
          <template slot-scope="scope">
            {{scope.row.sex==0?'男':(scope.row.sex==1?'女':'保密')}}
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="所属部门"
          width="100px"
          >
        </el-table-column>
        <el-table-column
          prop="birth"
          label="生日">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>

        <el-table-column
          prop="phoneNumber"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="status"
          label="是否禁用"
          width="100px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status==0"
              active-color="#13ce66"
              inactive-color="#C0CCDA"
              @change="upStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="getUpdate(scope.row.id)" title="修改" circle></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)" title="删除" circle></el-button>
            <el-button type="success" icon="el-icon-s-tools" title="设置" circle></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="margin: 15px 0px 0px 15px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[4, 5, 6, 7]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

<!--添加-->
      <div>
        <el-dialog v-bind="$attrs" v-on="$listeners" :visible.sync="insertDialog" @close="onClose" title="添加用户">
          <el-row :gutter="15">
            <el-form ref="elForm" :model="iUser" :rules="rules" size="medium" label-width="100px">
              <el-col :span="24">
                <el-form-item label="用户头像" prop="avatar" required>
                  <pan-thumb :image="image" />

                  <el-button type="primary" icon="el-icon-upload" style="position: absolute;bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
                    图片上传
                  </el-button>

                  <image-cropper
                    v-show="imagecropperShow"
                    :key="imagecropperKey"
                    :width="300"
                    :height="300"
                    url="/aliOss/uploadImgFile"
                    field="file"
                    @close="close"
                    @crop-upload-success="cropSuccess"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="iUser.username" placeholder="请输入用户名" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门" prop="departmentId">
                  <el-select v-model="iUser.departmentId" placeholder="请选择部门" clearable :style="{width: '100%'}">
                    <el-option
                      v-for="item in deptList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="iUser.nickname" placeholder="请输入昵称" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机" prop="phoneNumber">
                  <el-input v-model="iUser.phoneNumber" placeholder="请输入手机" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="iUser.sex" size="medium">
                    <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                              :disabled="item.disabled">{{item.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="password">
                  <el-input v-model="iUser.password" placeholder="请输入密码" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="iUser.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="生日" prop="birth">
                  <el-date-picker v-model="iUser.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                  :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
                </el-form-item>
              </el-col>

            </el-form>
          </el-row>
          <div slot="footer">
            <el-button @click="insertDialog=false">取消</el-button>
            <el-button type="primary" @click="addUser">确定</el-button>
          </div>
        </el-dialog>
      </div>

      <UpdateUser :updateDialog="updUser" :deList="deptList" :id="updateId" @updateShow="addUpdate"  ></UpdateUser>

    </el-card>
  </div>
</template>

<script>
  import {selectPage,selectDeptList,insertUser,
    deleteImgFile,deleteUser,exportUserInfo,updateStatus} from "../../api/user"
  import ImageCropper from '../../components/ImageCropper'
  import PanThumb from '../../components/PanThumb'
  import UpdateUser from '../user/UpdateUser'

  export default {
    name: 'User',
    inheritAttrs: false,
    components: { ImageCropper, PanThumb ,UpdateUser},
    data:function(){
      return{
        user: {
          username: '',
          email: '',
          sex:null,
          departmentId: '',
          nickname: '',
          name:'',
        },
        tableData: [],
        currentPage4: 1,
        size:6,
        total:10,
        deptList: [],
        /*添加表单*/
        iUser: {
          avatar: null,
          username: undefined,
          departmentId: 1,
          nickname: undefined,
          sex: 0,
          password: undefined,
          email: undefined,
          phoneNumber: undefined,
          birth: null,
        },
        rules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
          departmentId: [{
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }],
          nickname: [{
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }],
          sex: [{
            required: true,
            message: '性别不能为空',
            trigger: 'change'
          }],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }],
          phoneNumber: [{
            required: true,
            message: '请输入手机',
            trigger: 'blur'
          }],
          birth: [{
            required: true,
            message: '请选择生日',
            trigger: 'change'
          }],
        },
        sexOptions: [{
          "label": "男",
          "value": 0
        }, {
          "label": "女",
          "value": 1
        }],
        insertDialog:false,
        /*图片上传*/
        imagecropperShow: false,
        imagecropperKey: 0,
        image: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
        /*  修改  */
        updUser: false,
        updateId: null,
      }
    },
    methods:{
      onSubmit() {
        this.selectPage();
      },
      resetUser() {
       this.user={};
      },
      handleSizeChange(val) {
        this.size=val;
        this.currentPage4=1;
        this.selectPage();

      },
      handleCurrentChange(val) {
        this.currentPage4=val;
        this.selectPage();
      },
      selectPage(){
        var $this=this;
        selectPage($this.currentPage4,$this.size,$this.user)
          .then(function (response) {
            if (response.data.success) {
              $this.total=response.data.data.userPages.total;
              $this.tableData=response.data.data.userPages.records;
            }
          })
          .catch(function (erro) {
            console.log("获取失败！");
          })
      },
      getSelectDeptList(){
        var $this=this;
        selectDeptList()
          .then(function (response) {
            $this.deptList=response.data.data.deptList;

          })
          .catch(function (erro) {
            console.log("获取失败！");
          })
      },
      onClose() {
        this.$refs['elForm'].resetFields()
      },
      addUser() {
        var $this=this;
        this.iUser.avatar= this.image;
        this.$refs['elForm'].validate(valid => {
          if (!valid){
            return;
          }else{
            insertUser(this.iUser)
              .then(function (response) {
                if (response.data.data.insert){
                  $this.insertDialog=false;
                  $this.$message.success("添加成功！");
                  $this.selectPage();
                }else {
                  $this.$message.error(response.data.message);
                }
              })
              .catch(function (erro) {
                console.log("获取失败！");
              })
          }
           /* return*/

        })
      },
      /*图片上传*/
      cropSuccess(resData) {
        console.log(resData)
        var oldImage = this.image;
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        this.image = resData.data.url
        this.delImge(oldImage);
      },
      close() {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
      },
      delImge(oldImage){
        deleteImgFile(oldImage)
          .then(function (response) {
            console.log(response.data.message);
          })
          .catch(function (erro) {
            console.log("获取失败！");
          })
      },
      /*  删除用户  */
      delUser(id){
        var $this=this;
        deleteUser(id)
          .then(function (response) {
            console.log(response.data)
            if (response.data.data.del) {
              $this.$message.success("删除成功！");
              $this.selectPage();
            }else{
              $this.$message.error(response.data.message);
            }
          })
          .catch(function (erro) {

          })
      },
      /*修改*/
      addUpdate(data){
        if (data) {
          this.updUser=false;
          this.selectPage();
        }else {
          this.updUser=false;
        }
      },
      getUpdate(id){
        this.updateId=id;
        this.updUser=true;
      },
      exportExcel(){
        var $this=this;
        exportUserInfo(this.user).then(res => {
          //这里没有返回数据,但是要在响应头中进行下载操作
          // 将二进制文件转化为可访问的url
          if(res.data.type=="application/vnd.ms-excel"){
            let url = window.URL.createObjectURL(new Blob([res.data]));
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "用户列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          }else if (res.data.type=="application/json") {
            $this.$message.error("您的权限不足");
          }
        }).catch(err => {

        })
      },
      upStatus(user){
        var $this=this;
        updateStatus(user.id,user.status)
          .then(res => {
            if (res.data.data.status){
              user.status=user.status==1?0:1;
            }else{
              $this.$message.error(res.data.message)
            }
          })
          .catch(err =>{
            console.log("获取失败！");
          })
      }
    },
    created:function () {
      this.selectPage();
      this.getSelectDeptList();
    },
  }
</script>

<style scoped>

  .text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }

  .box-card {
    width: 100%;
    margin: 15px 0px 0px 0px;
  }

  .formitem{
    margin-left: 20px;
  }
  .el-upload__tip {
    line-height: 1.2;
  }

</style>
